<?php

namespace Hansn\LaravelAddons\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use stdClass;
use Symfony\Component\Filesystem\Filesystem;

class CreateAddon extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'addon:create {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建插件模块';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->container['name'] = $this->container['model'] = ucwords($this->argument('name'));
        $this->container['namespace'] = config('addons.namespace', 'Addons');

        $this->generate();

        $this->info(' ' . $this->container['name'] . ' 插件成功安装。');
    }

    protected function rename($path, $target, $type = null)
    {
        $filesystem = new Filesystem;
        if ($filesystem->exists($path)) {
            if ($type == 'migration') {
                $timestamp = date('Y_m_d_his_');
                $target = str_replace("create", $timestamp . "create", $target);
                $filesystem->rename($path, $target, true);
                $this->replaceInFile($target);
            } else {
                $filesystem->rename($path, $target, true);
            }
        }
    }
    protected function copy($path, $target)
    {
        $filesystem = new Filesystem;
        if ($filesystem->exists($path)) {
            $filesystem->mirror($path, $target);
        }
    }
    protected function replaceInFile($path)
    {
        $name = $this->container['name'];
        $model = $this->container['model'];
        $namespace = $this->container['namespace'];
        $types = [
            '{Module}' => $name,
            '{module}' => strtolower($name),
            '{Model}' => $model,
            '{model}' => strtolower($model),            
            '{namespace}' => $namespace,
        ];

        foreach ($types as $key => $value) {
            if (file_exists($path)) {
                file_put_contents($path, str_replace($key, $value, file_get_contents($path)));
            }
        }
    }

    protected function unlink($path)
    {
        if (file_exists($path)) {
            unlink($path);
        }
    }

    protected function generate()
    {
        $module = $this->container['name'];
        $model = $this->container['model'];
        $Module = $module;
        $module = strtolower($module);
        $Model = $model;
        $targetPath = base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR . $Module);
        //copy folders
        $this->copy(config('addons.stubs.path')?:base_path('vendor/hansn/laravel-addons/stubs'), $targetPath);
        //replace contents
        $this->replaceInFile($targetPath . '/config/config.php');
        $this->replaceInFile($targetPath . '/Console/Kernel.php');
        $this->replaceInFile($targetPath . '/database/factories/ModelFactory.php');
        $this->replaceInFile($targetPath . '/database/migrations/create_model_table.php');
        $this->replaceInFile($targetPath . '/database/seeders/ModelDatabaseSeeder.php');
        $this->replaceInFile($targetPath . '/Http/Controllers/ModuleController.php');
        $this->replaceInFile($targetPath . '/Models/Model.php');
        $this->replaceInFile($targetPath . '/Providers/ModuleServiceProvider.php');
        $this->replaceInFile($targetPath.'/Providers/RouteServiceProvider.php');
        $this->replaceInFile($targetPath . '/resources/views/blade/index.blade.php');
        $this->replaceInFile($targetPath . '/resources/views/vue/index.blade.php');
        $this->replaceInFile($targetPath . '/resources/views/layouts/main.blade.php');        
        $this->replaceInFile($targetPath . '/resources/assets/js/routes.js');
        $this->replaceInFile($targetPath . '/resources/assets/js/components/home/Sidebar.vue');
        $this->replaceInFile($targetPath . '/routes/api.php');
        $this->replaceInFile($targetPath . '/routes/web.php');
        $this->replaceInFile($targetPath . '/tests/Feature/ModuleTest.php');
        $this->replaceInFile($targetPath . '/composer.json');
        $this->replaceInFile($targetPath . '/manifest.json');
        $this->replaceInFile($targetPath . '/vite.config.js');
        
        //unlink file
        $this->unlink($targetPath . '/Console/Commands/ModuleCommand.php');

        //rename
        $this->rename($targetPath . '/database/factories/ModelFactory.php', $targetPath . '/database/factories/' . $Model . 'Factory.php');
        $this->rename($targetPath . '/database/migrations/create_model_table.php', $targetPath . '/database/migrations/create_' . $module . '_table.php', 'migration');
        $this->rename($targetPath . '/database/seeders/ModelDatabaseSeeder.php', $targetPath . '/database/seeders/' . $Module . 'DatabaseSeeder.php');
        $this->rename($targetPath . '/Http/Controllers/ModuleController.php', $targetPath . '/Http/Controllers/' . $Module . 'Controller.php');
        $this->rename($targetPath . '/Models/Model.php', $targetPath . '/Models/' . $Model . '.php');
        $this->rename($targetPath . '/Providers/ModuleServiceProvider.php', $targetPath . '/Providers/' . $Module . 'ServiceProvider.php');
        $this->rename($targetPath . '/tests/Feature/ModuleTest.php', $targetPath . '/tests/Feature/' . $Module . 'Test.php');
        $json = new stdClass;
        if (file_exists(base_path(config('addons.path', 'addons'). DIRECTORY_SEPARATOR .'addons.json')))
        {
            $json = json_decode(file_get_contents(base_path(config('addons.path', 'addons'). DIRECTORY_SEPARATOR .'addons.json')));
        }
        $json->$Module = false;
        file_put_contents(base_path(config('addons.path', 'addons'). DIRECTORY_SEPARATOR .'addons.json'), json_encode($json,JSON_PRETTY_PRINT));

    }

}
